package dbs

import (
	"github.com/gogap/logs"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"sync"
	"time"
	"yundian/internel/pkg/dingo/global"
)

type TransactionMap struct {
	sync.Map
}

var TransactionRecord = TransactionMap{} // 事务记录

// 初始化 Gorm
func GormDB(cfg *global.MysqlConfig) (*gorm.DB, error) {
	db, err := gorm.Open(mysql.Open(cfg.Source), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetMaxOpenConns(10)
	sqlDB.SetConnMaxLifetime(time.Second * 120)
	return db.Debug(), nil
}

// 开始事务
func GormBegin(description string) (*gorm.DB, string) {
	key := time.Now().Format("20060102150405") + "-" + description
	logs.Info("GormBegin", key)
	TransactionRecord.Store(key, "")
	return global.Orm.Begin(), key
}

// 事务回滚
func GormRollback(tx *gorm.DB, key string, err error) {
	TransactionRecord.Delete(key)
	logs.Error("GormRollback", key, err)
	tx.Rollback()
}

// 事务提交
func GormCommit(tx *gorm.DB, key string) {
	TransactionRecord.Delete(key)
	logs.Info("GormCommit", key)
	tx.Commit()
}
